import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Table,
  Space,
  Button,
  Input,
  Checkbox,
  Popconfirm,
  Divider,
  Drawer,
  Tabs,
  message,
  Select,
  Row,
  Col,
  Modal,
} from 'antd';
import {
  SyncOutlined,
  PlusOutlined,
  ArrowDownOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { connect, useIntl } from 'umi';
import TenantEdit from './components/tenantEdit';
import SyscfgEdit from './components/syscfgEdit';
import moment from 'moment';
import MyDataTable from '@/components/MyDataTable';
import request from '@/utils/request';

const apiURL = '/api/services/app/AuthCards/';
const apiURL2 = '/api/services/app/Tenant/';
const { Search } = Input;
const { TabPane } = Tabs;
const { Option } = Select;
const { confirm } = Modal;

const ViewPage = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [visible, setVisible] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [pageIndex, setPageIndex] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalCount, setTotalCount] = useState(0);
  const [authItems, setAuthItems] = useState<any[]>([]);
  const [record, setRecord] = useState<any>({});
  const [keywords, setKeywords] = useState('');
  const [freshNum, setFreshNum] = useState(1);
  const [days, setDays] = useState('30');
  const [count, setCount] = useState('100');
  const [params, setParams] = useState<any>({});
  const [loading2, setLoading2] = useState(false);
  const [authCodes, setAuthCodes] = useState('');
  const [visible2, setVisible2] = useState(false);
  const [tenantid, setTenantid] = useState(null);
  const [isUse, setIsUse] = useState('0');
  const intl = useIntl();

  useEffect(() => {
    fetchDatas();
  }, [pageIndex, pageSize, keywords]);

  const fetchDatas = () => {
    setLoading(true);
    request(apiURL2 + 'GetList', {
      method: 'GET',
      params:{ SkipCount: (pageIndex - 1) * pageSize, MaxResultCount: pageSize, keywords }
    }).then((response) => {
      if (response && response.success) {
        setDataSource(response.result.items);
        setTotalCount(response.result.totalCount);        
      }
      setLoading(false);
    });
  };

  const fetchDatas2 = () => {
    setFreshNum(freshNum + 1);
  };

  const handleDelete = (id: number) => {
    request(apiURL2 + 'Delete', {
      method: 'DELETE',
      data:{ id }
    }).then((response) => {
      if (response && response.success) {
        fetchDatas();
      }
    });
  };

  const onSelectChange = (selectedRowKeys: any) => {
    setSelectedRowKeys(selectedRowKeys);
  };

  const onSearch = (keywords: any) => {
    setKeywords(keywords);
  };

  const onSearch2 = (keywords: any) => {
    const params = {
      keywords,
      days,
      isUse,
    };
    console.log(params);
    
    setParams(params);
    fetchDatas2();
  };

  const swithDrawer = (visible: boolean, record = null) => {
    setVisible(visible);
    setRecord(record);
  };

  const setRowSelection = (items: any) => {
    setAuthItems(items);
  };

  const authCodeCreate = () => {
    confirm({
      title: intl.formatMessage({id: 'pages.warning'}),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({id: 'pages.createAuthCode?'}),
      onOk() {
        setLoading2(true);
        request(apiURL + 'CreateCards', {
          method: 'POST',
          params: {
            count,
            authProd: 'OPERP',
            authRevNo: '1.0',
            days,
          },
        }).then((response) => {
          if (response) {
            if (response.success) {
              setFreshNum(freshNum + 1);
            }
            setLoading2(false);
          }
        });
      },
      onCancel() {},
    });
  };

  const getCodeCreate = () => {
    setLoading2(true);
    request(apiURL + 'GetCodes', {
      method: 'GET',
      params: {
        days,
        isUse,
        keywords,
      },
    }).then((response) => {
      if (response) {
        if (response.success) {
          let authCodes = '';
          response.result.forEach((element: any) => {
            authCodes += element.cardNo + ' ' + element.cardPwd + '\n';
          });
          setAuthCodes(authCodes);
        }
        setLoading2(false);
      }
    });
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: intl.formatMessage({id: 'pages.tenancyName'}),
      dataIndex: 'tenancyName',
    },
    {
      title: intl.formatMessage({id: 'pages.otherName'}),
      dataIndex: 'name',
    },
    {
      title: intl.formatMessage({id: 'pages.telphone'}),
      dataIndex: 'telphone',
    },
    {
      title: intl.formatMessage({id: 'pages.isActive'}),
      dataIndex: 'isActive',
      render: (text: boolean) => <Checkbox checked={text} />,
    },
    {
      title: intl.formatMessage({id: 'pages.trialPeriod'}),
      render: (record: any) =>
        record.effectDate
          ? moment(record.effectDate).format('YYYY-MM-DD') +
            ' 至 ' +
            moment(record.endDate).format('YYYY-MM-DD')
          : '',
    },
    {
      title: intl.formatMessage({id: 'pages.operation'}),
      render: (record: any) =>
        dataSource.length >= 1 ? (
          <span>
            <Popconfirm title={intl.formatMessage({id: 'pages.delete?'})} onConfirm={() => handleDelete(record.id)}>
              <a>{intl.formatMessage({id: 'pages.delete'})}</a>
            </Popconfirm>
            <Divider type="vertical" />
            <a onClick={() => swithDrawer(true, record)}>{intl.formatMessage({id: 'pages.edit'})}</a>
            <Divider type="vertical" />
            <a onClick={() => {setVisible2(true);setTenantid(record.id)}}>{intl.formatMessage({id: 'pages.version'})}</a>
          </span>
        ) : null,
    },
  ];

  const column2 = [
    {
      title: intl.formatMessage({id: 'pages.authCode'}),
      dataIndex: 'cardNo',
    },
    {
      title: intl.formatMessage({id: 'pages.authProd'}),
      dataIndex: 'authProd',
    },
    {
      title: intl.formatMessage({id: 'pages.authRevNo'}),
      dataIndex: 'authRevNo',
    },
    {
      title: intl.formatMessage({id: 'pages.authDays'}),
      dataIndex: 'authDays',
    },
    {
      title: intl.formatMessage({id: 'pages.used'}),
      dataIndex: 'isUse',
      render: (text: boolean) => <Checkbox checked={text} />,
    },
    {
      title: intl.formatMessage({id: 'pages.useTime'}),
      render: (record: any) =>
        record.useTime ? moment(record.useTime).format('YYYY-MM-DD hh:mm:ss') : '',
    },
    {
      title: 'ID',
      dataIndex: 'id',
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const zhang = intl.formatMessage({id:'pages.zhang'});
  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Card>
        <Tabs defaultActiveKey="1">
          <TabPane tab={intl.formatMessage({id: 'menu.admin.tenants'})} key="1">
            <Space style={{ marginBottom: 16 }}>
              <Button
                type="primary"
                onClick={fetchDatas}
                loading={loading}
                icon={<SyncOutlined />}
              >
                <span>{intl.formatMessage({id: 'pages.refresh'})}</span>
              </Button>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => swithDrawer(true)}
              >
                <span>{intl.formatMessage({id: 'pages.new'})}</span>
              </Button>
              <Search
                style={{ width: 240 }}
                placeholder={intl.formatMessage({id: 'pages.enterKeywords'})}
                onSearch={(value) => onSearch(value)}
              />
            </Space>

            <Table
              rowKey="id"
              loading={loading}
              rowSelection={rowSelection}
              columns={columns}
              dataSource={dataSource}
              pagination={{
                onChange: (page) => {
                  setPageIndex(page);
                },
                pageSize,
                total: totalCount,
              }}
            />
          </TabPane>
          <TabPane tab={intl.formatMessage({id: 'pages.authCode'})} key="2">
            <Space style={{ marginBottom: 16 }}>
              <Button
                type="primary"
                onClick={fetchDatas2}
                loading={loading}
                icon={<SyncOutlined />}
              >
                <span>{intl.formatMessage({id:'pages.refresh'})}</span>
              </Button>
              <Select defaultValue="-1" onChange={(val) => setIsUse(val)}>
                <Option value="1">{intl.formatMessage({id:'pages.used'})}</Option>
                <Option value="0">{intl.formatMessage({id:'pages.unUsed'})}</Option>
                <Option value="-1">{intl.formatMessage({id:'pages.all'})}</Option>
              </Select>
              <Select defaultValue="365" onChange={(val) => setDays(val)}>
                <Option value="7">{intl.formatMessage({id:'pages.servenDays'})}</Option>
                <Option value="30">{intl.formatMessage({id:'pages.oneMonth'})}</Option>
                <Option value="183">{intl.formatMessage({id:'pages.halfYear'})}</Option>
                <Option value="365">{intl.formatMessage({id:'pages.oneYear'})}</Option>
                <Option value="1095">{intl.formatMessage({id:'pages.threeYears'})}</Option>
                <Option value="1825">{intl.formatMessage({id:'pages.fiveYears'})}</Option>
                <Option value="3650">{intl.formatMessage({id:'pages.tenYears'})}</Option>
              </Select>
              <Select defaultValue="100" onChange={(val) => setCount(val)}>
                <Option value="50">50{zhang}</Option>
                <Option value="100">100{zhang}</Option>
                <Option value="500">500{zhang}</Option>
                <Option value="1000">1000{zhang}</Option>
                <Option value="3000">3000{zhang}</Option>
              </Select>

              <Search
                style={{ width: 240 }}
                placeholder={intl.formatMessage({id:'pages.enterKeywords'})}
                onSearch={(value) => onSearch2(value)}
              />
            </Space>
            <Row gutter={16}>
              <Col span={18}>
                <MyDataTable
                  act="GetList"
                  columns={column2}
                  freshNum={freshNum}
                  pageSize={pageSize}
                  control="AuthCards"
                  rowSelection={(items: any) => setRowSelection(items)}
                  params={params}
                  bordered={false}
                />
              </Col>
              <Col span={6}>
                <Space>
                  <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={() => authCodeCreate()}
                    loading={loading2}
                  >
                    <span>{intl.formatMessage({id:'pages.createAuthCode'})}</span>
                  </Button>
                  <Button
                    type="primary"
                    icon={<ArrowDownOutlined />}
                    onClick={() => getCodeCreate()}
                    loading={loading2}
                  >
                    <span>{intl.formatMessage({id:'pages.getAuthCode'})}</span>
                  </Button>
                </Space>
                <Input.TextArea rows={20} value={authCodes} placeholder={intl.formatMessage({id:'pages.authCode'})} />
              </Col>
            </Row>
          </TabPane>
        </Tabs>
      </Card>
      <Drawer
        width={800}
        placement="right"
        closable={false}
        onClose={() => swithDrawer(false)}
        visible={visible}
        destroyOnClose={true}
      >
        <TenantEdit ParentData={record} fetchDatas={fetchDatas} />
      </Drawer>
      <Modal
        title={intl.formatMessage({id:'pages.version'})}
        visible={visible2}
        destroyOnClose={true}
        onCancel={() => setVisible2(false)}
        footer={false}
      >
        <SyscfgEdit tenantid={tenantid} />
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
